<template>
  <el-dialog :model-value="visible" :title="title" width="500" :close-on-click-modal="false" :show-close="false">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-form-item label="字典类别">
        <el-input disabled :model-value="dictName"></el-input>
      </el-form-item>
      <el-form-item label="字典名称" prop="name">
        <el-input @change="getPy" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="字典编码" prop="code">
        <el-input :disabled="props.data !== null" v-model="form.code"></el-input>
      </el-form-item>
      <el-form-item label="排序值" prop="orderBy">
        <el-input-number :min="0" :step="1" v-model.number="form.orderBy"></el-input-number>
      </el-form-item>
      <span v-if="showTip" style="color: red;">注：ADMIN、USER为系统内置角色，不能设置为字典编码！</span>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="emits('close', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import ApiTree from '@/server/api-tree';
import { DictTypeList, type DictVO } from '@/server/dict/types';
import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';

const emits = defineEmits(["close"])
const props = withDefaults(defineProps<
  {
    dictType: string; data: DictVO | null, visible: boolean
  }>(), {
  dictType: "",
  data: null,
  visible: false
});
/** 表单定义 */
const dictName = ref("");
const title = ref<string>("");
const form = ref<DictVO>({
  guid: "",
  dictType: "",
  code: "",
  name: "",
  orderBy: 0,
  ctime: "",
  cuser: "",
});
const formRef = ref<FormInstance>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const codeValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("字典编码不能为空"));
  }
  if (value === "DEMO") {
    return callback(new Error("字典编码不能是DEMO"));
  }
  callback();
}
const formRules = reactive<FormRules<DictVO>>({
  code: [{ required: true, validator: codeValidator }],
  name: [{ required: true, message: "字典名称不能为空" }],
  orderBy: [{ required: true, message: "排序值不能小于0" }]
})
const initForm = () => {
  form.value = {
    guid: "",
    dictType: props.dictType,
    code: "",
    name: "",
    orderBy: 0,
    ctime: "",
    cuser: "",
  }
}

/**
 * 监听属性变化
 */
const showTip = ref(false);
watch(() => props.visible, () => {
  if (props.data) {
    title.value = "编辑字典"
    form.value = props.data;
  } else {
    title.value = "添加字典"
    initForm();
  }
  showTip.value = props.dictType === "ROLE";
  dictName.value = DictTypeList.find(x => x.type === props.dictType)?.name ?? ""
}, { immediate: true })
const getPy = async () => {
  if (props.data) return; // 如果是编辑，则不允许修改code
  const { success, data } = await ApiTree.common.getPy(form.value.name);
  if (success) {
    form.value.code = data;
  }
}
/**提交表单 */
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      //
      if (props.data) {
        const { success, msg } = await ApiTree.dict.update(form.value);
        if (success) {
          ElMessage.success(msg);
        }
        emits("close", success);
      } else {
        const { success, msg } = await ApiTree.dict.create(form.value);
        if (success) {
          ElMessage.success(msg);
        }
        emits("close", success);
      }
    }
  })
}
</script>
<style lang="scss" scope></style>
